<template>
  <div>
    <van-nav-bar title="配送地址列表" left-arrow @click-left="$router.go(-1)" />
    <van-address-list v-if="addressList.length > 0" v-model="chosenAddressId" :list="formatAddressList" default-tag-text="默认"
      @add="addDialog=true" @edit="onEdit" />
    <div class="empty-cart" v-else>
      <img src="@/assets/empty.png" alt="">
      <div class="tips">
        您还没有添加配送地址, 快去添加吧
      </div>
      <div class="btn" @click="addDialog = true">新增地址</div>
    </div>

    <!-- 新增配送地址活动面板 -->
    <van-action-sheet v-model="addDialog" :title="`${isEdit?'编辑':'新增'}配送地址`" @cancel="onCancel">
      <van-address-edit :area-list="areaList" :address-info="form" show-search-result
        :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="saveAddress" />
    </van-action-sheet>
  </div>
</template>
<script>
import { addPostAddress, getDetailAddress, editPostAddress } from '@/api/pay'
import { areaList } from '@vant/area-data'
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'AddressList',
  data () {
    return {
      areaList,
      addDialog: false,
      form: {
        id: '',
        name: '',
        tel: '',
        addressDetail: '',
        areaCode: ''
      },
      formInit: {
        id: '',
        name: '',
        tel: '',
        addressDetail: '',
        areaCode: ''
      }
      // form: {
      //   name: '',
      //   phone: '',
      //   region: [],
      //   detail: ''
      // }
    }
  },
  computed: {
    ...mapState('cart', ['addressList', 'regions']),
    ...mapGetters('cart', ['formatAddressList']),
    chosenAddressId: {
      get () {
        return this.$store.state.cart.defaultAddressId
      },
      set (value) {
        this.$store.dispatch('cart/setDefaultAction', value)
      }
    },
    isEdit () {
      return !!this.form.id
    }
  },
  created () {
    this.getAddressList()

    this.getRegions()
  },
  methods: {
    getRegions () {
      this.$store.dispatch('cart/getRegions')
    },
    getAddressList () {
      this.$store.dispatch('cart/getAddressList')
    },
    onCancel () {
      this.form = this.formInit
    },

    async saveAddress (data) {
      const arr = []
      const pKeys = Object.keys(this.regions)
      let breakFor = false
      // 找省
      for (let i = 0; i < pKeys.length; i++) {
        if (breakFor) break
        const pObj = this.regions[pKeys[i]]
        if (data.province.includes(pObj.name)) {
          const province = { value: pObj.id, label: pObj.name }
          arr.push(province)
          // 找市
          const cKeys = Object.keys(pObj.city)
          for (let i = 0; i < cKeys.length; i++) {
            if (breakFor) break
            const cObj = pObj.city[cKeys[i]]
            if (data.city === cObj.name) {
              const city = { value: cObj.id, label: cObj.name }
              arr.push(city)
              // 找区
              const rKeys = Object.keys(cObj.region)
              for (let i = 0; i < rKeys.length; i++) {
                const rObj = cObj.region[rKeys[i]]
                if (data.county === rObj.name) {
                  const region = { value: rObj.id, label: rObj.name }
                  arr.push(region)
                  breakFor = true
                  break
                }
              }
            }
          }
        }
      }

      if (this.isEdit) {
        await editPostAddress(data.id, {
          name: data.name,
          phone: data.tel,
          region: arr,
          detail: data.addressDetail
        })
      } else {
        await addPostAddress({
          name: data.name,
          phone: data.tel,
          region: arr,
          detail: data.addressDetail
        })
      }
      await this.getAddressList()
      this.$toast({
        type: 'success',
        message: this.isEdit ? '编辑地址成功' : '新增地址成功'
      })
      this.addDialog = false
    },
    async onEdit (item, index) {
      const { data: { detail } } = await getDetailAddress(item.id)
      const obj = {}
      obj.id = detail.address_id
      obj.name = detail.name
      obj.tel = detail.phone
      obj.addressDetail = detail.detail

      // const region = detail.region.region
      const countyList = this.areaList.county_list
      const arr = Object.keys(countyList)
      for (let i = 0; i < arr.length; i++) {
        const val = countyList[arr[i]]
        if (val === detail.region.region) {
          obj.areaCode = arr[i]
        }
      }
      this.form = obj
      this.addDialog = true
    }
  }
}
</script>
<style lang="less" scoped>
.empty-cart {
  padding: 80px 30px;

  img {
    width: 140px;
    height: 92px;
    display: block;
    margin: 0 auto;
  }

  .tips {
    text-align: center;
    color: #666;
    margin: 30px;
  }

  .btn {
    width: 110px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    background-color: #fa2c20;
    border-radius: 16px;
    color: #fff;
    display: block;
    margin: 0 auto;
  }
}
.van-address-list__bottom {
  background: none;
}
</style>
